<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="/static/home/css/reset.css">
    <link rel="stylesheet" href="/static/home/plug/layui/css/layui.css">
    <title>人脸识别</title>
    <script type="text/javascript" src="/static/home/js/jquery-3.1.1.min.js"></script>
    <script src="/static/home/plug/layui/layui.js"></script>
    <script type="text/javascript" src="{__SGHOME_PATH}js/vconsole.min.js"></script>
    <script>
        var local_url="/static/admin/js/";
        var deviceWidth = document.documentElement.clientWidth;
        document.documentElement.style.fontSize = deviceWidth / 7.5 + 'px';
        // var vConsole = new window.VConsole();
    </script>
    <script src="/static/admin/js/base.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            background: #fff;
        }

        .content {
            border-bottom: 0.15rem solid #f4f4f4;
        }

        .list {
            font-size: 0.26rem;
            color: #666666;
            font-weight: 500;
            padding: 0 0.32rem;
            width: 7.5rem;
            border-bottom: 1px solid #e5e5e5;
            display: flex;
            height: 1.02rem;
            line-height: 1.02rem;
            justify-content: space-between;
        }

        .val {
            color: #333333;
            font-weight: bolder;
        }

        .value {
            font-weight: bolder;
            flex: 1;
            text-align: right;
            border: 0;
            font-size: 0.26rem;
        }

        .tl span, .bottom span {
            color: red;
            margin-right: 0.06rem;
            font-weight: bolder;
        }

        .bottom {
            font-size: 0.26rem;
            padding: 0.66rem 0.32rem 0;
            cursor: pointer;
        }

        .btn1 {
            width: 6.6rem;
            height: 0.84rem;
            background: #00BFFF;
            color: #fff;
            text-align: center;
            line-height: 0.84rem;
            border-radius: 0.42rem;
            font-size: 0.3rem;
            border: 1px solid #00BFFF;
            margin: .74rem auto 0.58rem;
            cursor: pointer;
            font-weight: bolder;
        }

        .btnwrapper {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin-top: 40px;
        }

        .btnwrapper .btn {
            display: block;
            width: 100%;
            height: 45px;
            line-height: 45px;
            text-align: center;
            border: solid 1px #33a6fa;
            border-radius: 20px;
            color: #33a6fa;
            font-size: 18px;
            margin: 0 0.32rem;
        }

        #imgshow {
            /*display: none;*/
            position: relative;
            text-align: center;
            margin: 0 0.32rem;
            margin-top: 15px;
        }
        #imgshow #rect {
            position: absolute;
            border: 2px solid #ffff00;
        }
        #imgshow img {
            width: 100%;
            height: 100%;
            border-radius: 10px;
        }

        .video-wrapper {
            position: relative;
            height: 100vh;
        }
        .wrapper {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 1000;
        }
        #video {
            position: relative;
            width: 100%;
            height: 100%;
            object-fit: cover;
            z-index: 1;
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
        .img-wrapper {
            height: 100%;
            width: 100%;
            opacity: .4;
        }
        .canvas-wrapper {
            margin: 0 auto;
            width: 320px;
        }
        #imgView {
            margin: 0 auto;
            width: 320px;
            text-align: center;
        }
        #capture {
            position: absolute;
            bottom: 4px;
            left: calc(50% - 42px);
            height: 80px;
            width: 80px;
            padding: 4px;
            border-radius: 50%;
            border: none;
            padding-top: 25px;
            padding-left: 6px;
            color: #00BFFF;
        }
        #closeBtn {
            position: absolute;
            top: 0px;
            right: 0px;
            padding: 8px 10px;
            border: none;
        }
        #closeBtn .close {
            width: 0.8rem;
            height: 0.8rem;
        }
        #openBtn {
            position: absolute;
            top: 0px;
            right: 0px;
            padding: 8px 10px;
            border-radius: 2px;
        }
        #imgTip {
            position: absolute;
            width: 200px;
            /* margin: 0 auto; */
            top: 100px;
            left: 50%;
            margin-left: -90px;
            color: #00BFFF;
        }
        .rect {
            border: 2px solid #a64ceb;
            left: -1000px;
            position: absolute;
            top: -1000px;
            z-index: 1100;
        }

        video::-webkit-media-controls-start-playback-button {
            display: none;
        }

        video::-moz-media-controls-play-button {
            display: none;
        }

        video::-o-media-controls-play-button {
            display: none;
        }

        video::-ms-media-controls-play-button {
            display: none;
        }

    </style>
</head>
<body>
<div class="video-wrapper" style="display: none;text-align: center;">
    <!-- 视频遮罩层 -->
    <div class="wrapper">
        <div id="imgTip"><h3>点击下方手机图标拍照</h3></div>
        <img class="img-wrapper" id="imgWrap" src="{__SGHOME_PATH}images/face-wrappernew.jpg"/>
        <button id="capture">拍照</button>
        <button id="closeBtn"><img class="close" src="{__SGHOME_PATH}images/address_edit_clear.png" alt=""/></button>
    </div>
    <!-- video用于显示媒体设备的视频流，自动播放 -->
    <video id="video" style="display: none;" muted
           x5-playsinline="true"
           playsinline="true"
           webkit-playsinline="true"
           x-webkit-airplay="true"
           x5-video-orientation="portraint" ></video>

</div>

<div class="canvas-wrapper" style="display: none;">
    <canvas id="canvas" width="540" height="960"></canvas>
</div>

<form class="layui-form">

    <input type="hidden" name="user_id" value="{$homeuser_info.user_id}"/>

    <div class="content">
        <div class="list">
            <div class="tl"><span>*</span>姓名</div>
            <input class="value" value="{$homeuser_info.username}"/>
        </div>
    </div>

    <div id="imgshow">
        <img src="{if $homeuser_info.faceimg}{$homeuser_info.faceimg}{else}{$homeuser_info.avatar_origin}{/if}" id="img" />
    </div>

    <div class="btnwrapper">
        <div id="btnUploadImg_rjimg" class="btn">拍照</div>
        <input class="layui-upload-file" id="imgInp" type="file" accept="image/*" capture="camera">
        <input type="hidden" id="faceimg" name="faceimg" value="">
        <input type="hidden" id="faceimgid" name="faceimgid" value="">
    </div>

    <div class="bottom">
        <div class="tlt"><span onclick="window.location.href='https://gtportal.feishu.cn/wiki/L4abwRb2cixLFMkZombcA5wKnvf?chunked=false';">点击查看人脸录入及选取照片要求</span></div>
    </div>

    <div class="btn btn1" lay-submit="" lay-filter="add">提交</div>

</form>
</body>
<script src="/static/home/js/tracking-min.js"></script>
<script src="/static/home/js/face-min.js"></script>
<script type="text/javascript">

    layui.use(['element', 'form', 'jquery', 'laydate', 'lucky'], function () {

        var element = layui.element;
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;
        var laydate = layui.laydate;
        var upload = layui.upload;
        var lucky = layui.lucky;

        form.render();

        var screenSize = {width: window.screen.width, height: window.screen.height};
        var video_URL = null;
        var streamIns = null;        // 视频流
        var showContainer = true;   // 显示
        var tracker = null;
        var tipFlag = false;         // 提示用户已经检测到
        var flag = false;            // 判断是否已经拍照
        var context = null;          // canvas上下文
        var removePhotoID = null;    // 停止转换图片
        var scanTip = '人脸识别中...';// 提示文字
        var imgUrl = '';             // base64格式图片

        // 访问用户媒体设备
        function getUserMedia(constrains, success, error) {
            if (navigator.mediaDevices.getUserMedia) {
                //最新标准API
                navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                //webkit内核浏览器
                navigator.webkitGetUserMedia(constrains).then(success).catch(error);
            } else if (navigator.mozGetUserMedia) {
                //Firefox浏览器
                navagator.mozGetUserMedia(constrains).then(success).catch(error);
            } else if (navigator.getUserMedia) {
                //旧版API
                navigator.getUserMedia(constrains).then(success).catch(error);
            } else {
                layer.msg("你的浏览器不支持访问用户媒体设备");
                return false;
            }
        }

        // 成功的回调函数
        function success(stream){
            streamIns = stream
            //兼容webkit内核浏览器
            const CompatibleURL = window.URL || window.webkitURL;
            let video = document.getElementById("video");
            //将视频流设置为video元素的源
            if ("srcObject" in video) {
                video.srcObject = stream
            } else {
                video.src = video_URL.createObjectURL(stream)
            }
            video.onloadedmetadata = e => {
                video.style.display = 'block';
                // 播放视频
                video.play();
                // initTracker();
            }
        }

        // 异常的回调函数
        function error(error){
            video.style.display = 'none';
            layer.msg("访问用户媒体失败" + error.name + "," + error.message);
            return false;
        }

        function initTracker(){
            context = document.getElementById("canvas").getContext("2d");    // 画布
            tracker = new tracking.ObjectTracker(['face']);     // tracker实例
            tracker.setStepSize(1.7);                           // 设置步长
            tracker.on('track', handleTracked);          // 绑定监听方法
            try {
                tracking.track('#video', tracker);     // 开始追踪
            } catch (e) {
                layer.msg("访问用户媒体失败，请重试");
                return false;
            }
        }

        // 追踪事件
        function handleTracked(e) {
            console.log(e.data);
            if (e.data.length === 0) {
                /*layer.msg("未检测到人脸");
                return false;*/
                // document.getElementById("imgTip").innerText = '未检测到人脸!';
            } else {
                if (!tipFlag) {
                    document.getElementById("imgTip").innerText = '检测人脸成功，正在拍照，请保持不动2秒！';
                }
                // 2秒后拍照，仅拍一次
                if (!flag) {
                    flag = true
                    removePhotoID = setTimeout(() => {
                        tackPhoto();
                        tipFlag = true;
                    }, 2000)
                }
                e.data.forEach(window.plot);
            }
        }

        // 绘制跟踪框
        window.plot = function({x, y, width: w, height: h}) {
            // 创建框对象
            const rect = document.createElement('div');
            document.querySelector('.video-wrapper').appendChild(rect);
            rect.classList.add('rect');
            rect.style.width = w + 'px';
            rect.style.height = h + 'px';
            rect.style.left = (video.offsetLeft + x) + 'px';
            rect.style.top = (video.offsetTop + y) + 'px';
        };

        // 拍照
        function tackPhoto() {
            let video = document.getElementById("video");
            context.drawImage(video, 0, 0, screenSize.width, screenSize.height);
            // 保存为base64格式
            imgUrl = saveAsPNG(document.getElementById("canvas"))
            /** 拿到base64格式图片之后就可以在this.compare方法中去调用后端接口比较了，也可以调用getBlobBydataURI方法转化成文件再去比较
             * 我们项目里有一个设置个人头像的地方，先保存一下用户的图片，然后去拿这个图片的地址和当前拍照图片给后端接口去比较。
             * */
            console.log(imgUrl);
            console.log(convertCanvasToImage(document.getElementById("canvas")));
            // ajaxUploadBase64File(convertCanvasToImage(document.getElementById("canvas")));
            // ajaxUploadBase64File(imgUrl);
            document.getElementById("imgTip").innerText = '拍照完成！';
            // close();
            $(".video-wrapper").hide();
            $(".layui-form").show();
        }

        function close(){
            flag = false;
            tipFlag = false;
            showContainer = false;
            tracker && tracker.removeListener('track', handleTracked);
            tracker = null;
            context = null;
            scanTip = '人脸识别中...';
            clearTimeout(this.removePhotoID)
            if (streamIns) {
                streamIns.enabled = false;
                streamIns.getTracks()[0].stop();
                streamIns.getVideoTracks()[0].stop();
            }
            streamIns = null;
        }

        $("#btnUploadImg_rjimg").on('click',function (){
            $(".video-wrapper").show();
            $(".layui-form").hide();


            if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
                //调用用户媒体设备，访问摄像头
                getUserMedia({
                    video: {
                        width: 1920,
                        height: 1080,
                        facingMode: "user" // 前置优先
                    }
                }, success, error);
            } else {
                layer.msg("你的浏览器不支持访问用户媒体设备");
                return false;
            }

        });

        // 保存成png格式的图片
        function saveAsPNG(canvas) {
            return canvas.toDataURL("image/png");
        }

        // canvas to Image
        function convertCanvasToImage(canvas) {
            var image = new Image();
            image.src = canvas.toDataURL("image/png");
            return image;
        }

        $("#capture").on('click',function (){
            let video = document.getElementById("video");
            context = document.getElementById("canvas").getContext("2d");
            //绘制画面
            context.drawImage(video,0,0,540,960);
            // 保持图片为base64格式
            imgUrl = saveAsPNG(document.getElementById("canvas"))
            /** 拿到base64格式图片之后就可以在this.compare方法中去调用后端接口比较了，也可以调用getBlobBydataURI方法转化成文件再去比较
             * 我们项目里有一个设置个人头像的地方，先保存一下用户的图片，然后去拿这个图片的地址和当前拍照图片给后端接口去比较。
             * */
            // console.log(imgUrl);
            ajaxUploadBase64File(imgUrl);
        });


        $("#closeBtn").on('click',function (){
            $(".video-wrapper").hide();
            $(".layui-form").show();
        });

        $("#imgInp").change(function () {
            readURL(this);
        });

        function ajaxUploadBase64File(base64Data) {
            var url = "{:url('index/UpHomeImages')}";
            $.ajax({
                url: url,
                type: "post",
                data: {myPhoto: base64Data},
                dataType: "json",
                beforeSend:function(){
                    loading = layer.load(2, {
                        shade: [0.2, '#000'] //0.2透明度的白色背景
                    });
                },
                success: function (data) {
                    if (data.status == 200) {
                        layer.close(loading);
                        console.log("上传成功");
                        console.log(data);
                        // return false;
                        //上传完毕回调
                        $("#img").attr("src",data.msg);
                        $("#faceimg").val(data.msg);
                        $("#faceimgid").val(data.img_id);
                        $(".video-wrapper").hide();
                        $(".layui-form").show();
                        return false;
                    }
                    else {
                        console.log(data.msg);
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg("上传失败");
                    return false;
                }
            });
        };

        function readURL(input) {
            if (input.files && input.files[0]) {
                $('.loadingImg').css('display', 'flex');

                var reader = new FileReader();
                reader.onload = function (e) {
                    var base64 = null;
                    //图片方向角 added by lzk
                    var Orientation = null;
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var expectWidth = this.naturalWidth;
                        var expectHeight = this.naturalHeight;

                        if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                            expectWidth = 800;
                            expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                        } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
                            expectHeight = 1200;
                            expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                        }
                        var canvas = document.createElement("canvas");
                        var ctx = canvas.getContext("2d");
                        canvas.width = expectWidth;
                        canvas.height = expectHeight;
                        console.log(expectWidth);
                        ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
                        //修复ios
                        if (navigator.userAgent.match(/iphone/i)) {
                            console.log('iphone');
                            //alert(expectWidth + ',' + expectHeight);
                            //如果方向角不为1，都需要进行旋转 added by lzk
                            if (Orientation != "" && Orientation != 1) {
                                switch (Orientation) {
                                    case 6://需要顺时针（向左）90度旋转
                                        rotateImg(this, 'left', canvas);
                                        break;
                                    case 8://需要逆时针（向右）90度旋转
                                        rotateImg(this, 'right', canvas);
                                        break;
                                    case 3://需要180度旋转
                                        rotateImg(this, 'upside', canvas);
                                        break;
                                }
                            }
                            base64 = canvas.toDataURL("image/jpeg", 0.7);
                        } else if (navigator.userAgent.match(/Android/i)) {
                            // 修复android
                            //var encoder = new JPEGEncoder();
                            //base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth, expectHeight), 80);
                            base64 = canvas.toDataURL("image/jpeg", 0.7);
                        } else {
                            //alert(Orientation);
                            if (Orientation != "" && Orientation != 1) {
                                //alert('旋转处理');
                                switch (Orientation) {
                                    case 6://需要顺时针（向左）90度旋转
                                        rotateImg(this, 'left', canvas);
                                        break;
                                    case 8://需要逆时针（向右）90度旋转
                                        rotateImg(this, 'right', canvas);
                                        break;
                                    case 3://需要180度旋转
                                        rotateImg(this, 'upside', canvas);
                                        break;
                                }
                            }

                            base64 = canvas.toDataURL("image/jpeg", 0.8);
                        }
                        console.log('////11');
                        ajaxUploadBase64File(base64);
                    }
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        /**
         * 提交表单数据
         */
        form.on('submit(add)', function (data) {
            console.log(data.field);
            // return false;
            lucky.FormSubmit("{:url('index/face')}", data.field, 0 , 0 , "{:url('index/face')}");
            return false;
        });


    });

</script>
</html>